#pragma once
#include <assert.h>
#include "IState.h"


template <class entity_type>
class CStateMachine
{
private:

  //a pointer to the agent that owns this instance
  entity_type *           m_pOwner;

  IState<entity_type> *   m_pCurrentState;
  
  //a record of the last state the agent was in
  IState<entity_type> *   m_pPreviousState;

  //this is called every time the FSM is updated
  IState<entity_type> *   m_pGlobalState;
  

public:

  CStateMachine(entity_type * owner):m_pOwner(owner),
                                    m_pCurrentState(NULL),
                                    m_pPreviousState(NULL),
                                    m_pGlobalState(NULL)
  {
  }

  virtual ~CStateMachine(){}

  //use these methods to initialize the FSM
  void SetCurrentState(IState<entity_type>* s){m_pCurrentState = s;}
  void SetGlobalState(IState<entity_type>* s) {m_pGlobalState = s;}
  void SetPreviousState(IState<entity_type>* s){m_pPreviousState = s;}
  
  //call this to update the FSM
  void  Update(float dt)const
  {
    //if a global state exists, call its execute method, else do nothing
    if(m_pGlobalState)   m_pGlobalState->Execute(m_pOwner, dt);

    //same for the current state
    if (m_pCurrentState) m_pCurrentState->Execute(m_pOwner, dt);
  }

  //change to a new state
  void  ChangeState(IState<entity_type>* pNewState)
  {
    assert(pNewState && 
           "<StateMachine::ChangeState>: trying to change to NULL state");

    //keep a record of the previous state
    m_pPreviousState = m_pCurrentState;

	if(m_pCurrentState)
    //call the exit method of the existing state
		m_pCurrentState->Exit(m_pOwner);

    //change state to the new state
    m_pCurrentState = pNewState;

    //call the entry method of the new state
    m_pCurrentState->Enter(m_pOwner);
  }

  //change state back to the previous state
  void  RevertToPreviousState()
  {
    ChangeState(m_pPreviousState);
  }

  //returns true if the current state's type is equal to the type of the
  //class passed as a parameter. 
  bool  IsInState(const IState<entity_type>& st)const
  {
    return typeid(*m_pCurrentState) == typeid(st);
  }

  IState<entity_type>*  CurrentState()  const{return m_pCurrentState;}
  IState<entity_type>*  GlobalState()   const{return m_pGlobalState;}
  IState<entity_type>*  PreviousState() const{return m_pPreviousState;}
};


